﻿// News Framework
// (C) Tanzim Saqib. Oct 25, 2010.
// http://TanzimSaqib.com | http://newsfx.codeplex.com

namespace TanzimSaqib.NewsFramework
{
    using Microsoft.Phone.Tasks;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Windows;
    using System.Linq;
    using System;
    using System.Windows.Controls;

    public sealed class MainPanoramaViewModel : ViewModelBase
    {
        #region Properties

        private bool _HasSearchStarted = false;

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        public ObservableCollection<ItemViewModel> Latest { get; private set; }
        public ObservableCollection<ItemViewModel> Categories { get; private set; }
        public ObservableCollection<ItemViewModel> Saved { get; private set; }

        private string _PanoramaLatestHeader;
        public string PanoramaLatestHeader 
        { 
            get { return _PanoramaLatestHeader; }

            private set
            {
                _PanoramaLatestHeader = value;
                RaisePropertyChanged("PanoramaLatestHeader");  
            }
        }

        private bool _CanSearch;
        public bool CanSearch
        {
            get { return _CanSearch; }

            private set
            {
                _CanSearch = value;
                RaisePropertyChanged("CanSearch");
            }
        }

        private string _SearchText;
        public string SearchText 
        {
            get { return _SearchText; }

            private set
            {
                _SearchText = value;
                RaisePropertyChanged("SearchText");
            }
        }

        #endregion

        public MainPanoramaViewModel()
        {
            if(!IsDataLoaded)
            {
                PanoramaLatestHeader = "最近更新";

                Latest = new ObservableCollection<ItemViewModel>();
                Categories = new ObservableCollection<ItemViewModel>();
                Saved = new ObservableCollection<ItemViewModel>();

                if(!Fx.IsDesignMode)
                {
                    SearchText = string.Empty;
                    CanSearch = VerifyCanSearch();
                    BackgroundImageSource = PhoneUI.GetBackgroundBrush();
                }
            }

            IsDataLoaded = false;
        }

        #region Methods

        private void ProcessLatest(List<RssItem> items)
        {
            Latest.Clear();

            foreach (var item in items)
            {
                Latest.Add(new ItemViewModel() { LineOne = item.Title, LineTwo = item.ThumbnailURL, LineThree = item.Link });
            }
        }

        private void LoadLatest()
        {
            Feed _Feed;
            var feed = new FeedInfo(string.Empty, string.Empty, Fx.Instance.Feeds.Main);
            FeedData.LoadFromStorage();

            if (FeedData.Feeds.ContainsKey(Fx.Instance.Feeds.Main))
            {
                _Feed = FeedData.Feeds[Fx.Instance.Feeds.Main];

                if (_Feed.Items != null && _Feed.Items.Count > 0)
                {
                    ProcessLatest(_Feed.Items);
                }
                else
                {
                    PanoramaLatestHeader = FxConstants.StatusUpdating;
                }
            }
            else
            {
                PanoramaLatestHeader = FxConstants.StatusUpdating;
            }

            FeedData.Load(feed, (feedResponse) => 
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (feedResponse.Error == default(Exception))
                        {
                            _Feed = feedResponse.Item;

                            if (_Feed.IsLoaded &&_Feed.Items != null && _Feed.Items.Count > 0)
                            {
                                ProcessLatest(_Feed.Items);
                                PanoramaLatestHeader = FxConstants.LatestHeader;
                            }
                            else
                            {
                                PanoramaLatestHeader = FxConstants.StatusUpdateFailed;
                            }
                        }
                        else
                        {
                            PanoramaLatestHeader = FxConstants.StatusUpdateFailed;
                            MessageBox.Show(FxConstants.ConnectionError, string.Empty, MessageBoxButton.OK);
                        }
                    }));
        }

        public void LoadData()
        {
            LoadLatest();
            LoadCategories();
            LoadSaved();

            IsDataLoaded = true;
        }

        private void LoadSaved()
        {
            this.Saved.Clear();

            var savedItems = (from i in FeedData.RSSItems select i.Value).ToList();
            foreach (var savedItem in savedItems)
            {
                Saved.Add(new ItemViewModel() { LineOne = savedItem.Title, LineTwo = savedItem.ThumbnailURL, LineThree = savedItem.Link });
            }
        }

        private void LoadCategories()
        {
            this.Categories.Clear();

            foreach (var feed in Fx.Instance.Feeds)
            {
                Categories.Add(new ItemViewModel() { LineOne = feed.Key, LineTwo = feed.Value.Subtitle, LineThree = feed.Value.URL });
            }
        }

        #endregion

        #region Event Handlers

        public void MainPanorama_Load(CommandArgs args)
        {
            if (!IsDataLoaded)
            {
                LoadData();
            }
            else
            {
                LoadSaved();
            }
        }

        public void LoadPanorama(CommandArgs args)
        {
        }

        public void Latest_SelectionChanged(CommandArgs args)
        {
            var listBox = args.Source as ListBox;

            if (listBox.SelectedIndex > -1)
            {
                Fx.Instance.GoToPageInAssembly(FxConstants.LocalNamespace, FxConstants.RssViewLatestXaml.FormatWith(listBox.SelectedIndex));
            }
        }

        public void Categories_SelectionChanged(CommandArgs args)
        {
            var listBox = args.Source as ListBox;

            if (listBox.SelectedIndex > -1)
            {
                Fx.Instance.GoToPageInAssembly(FxConstants.LocalNamespace, FxConstants.RssListXamlPath.FormatWith(((ItemViewModel) listBox.SelectedItem).LineOne));
            }
        }

        public void Saved_SelectionChanged(CommandArgs args)
        {
            var listBox = args.Source as ListBox;

            if (listBox.SelectedIndex > -1)
            {
                Fx.Instance.GoToPageInAssembly(FxConstants.LocalNamespace, FxConstants.RssViewSavedXaml.FormatWith((listBox.SelectedItem as ItemViewModel).LineThree));
            }
        }

        public void SearchText_TextChanged(CommandArgs args)
        {
            // Two way binding for TextBox doesn't work.
            var textBox = args.Source as TextBox;
            SearchText = textBox.Text;

            CanSearch = VerifyCanSearch();
        }

        private bool VerifyCanSearch()
        {
            return !string.IsNullOrEmpty(SearchText) && !_HasSearchStarted;
        }

        public void Search_Click(CommandArgs args)
        {
            var homepage = Fx.Instance.Settings[FxConstants.AppHomepage].Replace("http://", string.Empty).Replace("https://", string.Empty).Replace("www.", string.Empty);
            var searchTask = new SearchTask()
            {
                SearchQuery = "{0} site:{1}".FormatWith(SearchText, homepage)
            };
            searchTask.Show();
            _HasSearchStarted = true;
        }

        //public void VisitHomePage(CommandArgs args)
        //{
        //    var browser = new WebBrowserTask { URL = FxConstants.HomePageURL };
        //    browser.Show();
        //}

        #endregion
    }
}
